package cn.tedu.es.es;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchOperations;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class StudentSearcher {
    // 用来执行查询的工具
    // 可以执行 CriteriaQuery、StringQuery、NativeQuery
    @Autowired
    private SearchOperations searchOperations;
    public List<Student> findByBirthDate(String birthDate) {
        //通过条件对象设置过滤条件
        Criteria criteria = new Criteria("birthDate").is(birthDate);
        return exec(criteria, null);
    }
    public List<Student> findByBirthDateBetween(String from, String to, Pageable pageable) {
        //通过条件对象设置过滤条件
        Criteria criteria = new Criteria("birthDate").between(from, to);
        return exec(criteria, pageable);
    }
    private List<Student> exec(Criteria criteria, Pageable pageable) {
        // 把条件封装成查询
        CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
        if (pageable != null) {
            criteriaQuery.setPageable(pageable); //设置分页查询
        }

        // 执行查询
        SearchHits<Student> hits = searchOperations.search(criteriaQuery, Student.class);
        List<Student> list = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        return list;
    }
}
